package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    //定义一个全局变量存取用户下单的订单id
    private Long orderId;

    @Value("${sky.shop.address}")//获取配置文件中的值
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

        //用户下单
        @Override
        public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
            //异常情况的处理（收货地址为空、超出配送范围、购物车为空）
            AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
            if(addressBook == null){
                throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
            }

            //检查客户的收货地址是否超出配送范围
            checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName()+ addressBook.getDetail());

            Long userId = BaseContext.getCurrentId();
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);

            //查询当前用户的购物车数据
            List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
            if(shoppingCartList == null){
                throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
            }

            //构造订单数据
            Orders orders = new Orders();
            BeanUtils.copyProperties(ordersSubmitDTO, orders);
            orders.setAddress(addressBook.getDetail());
            orders.setConsignee(addressBook.getConsignee());
            orders.setPhone(addressBook.getPhone());
            orders.setNumber(String.valueOf(System.currentTimeMillis()));
            orders.setUserId(userId);
            orders.setStatus(Orders.PENDING_PAYMENT);
            orders.setPayStatus(Orders.UN_PAID);
            orders.setOrderTime(LocalDateTime.now());

            //向订单表插入1条数据
            orderMapper.insert(orders);

            //将订单id存入全局变量
            orderId = orders.getId();

            //订单明细数据
            ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
            for (ShoppingCart cart : shoppingCartList) {
                OrderDetail orderDetail = new OrderDetail();
                BeanUtils.copyProperties(cart, orderDetail);
                orderDetail.setOrderId(orders.getId());
                orderDetailList.add(orderDetail);
            }
            //向明细表插入n条数据

            orderDetailMapper.insertBatch(orderDetailList);

            //清理购物车中的数据
            shoppingCartMapper.deleteByUserId(userId);



            //封装返回结果
            OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                    .id(orders.getId())
                    .orderNumber(orders.getNumber())
                    .orderAmount(orders.getAmount())
                    .orderTime(orders.getOrderTime())
                    .build();
            log.info("用户下单成功：{}", orderSubmitVO);

            return orderSubmitVO;
        }

    //订单支付（修改点）
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {


        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));


        JSONObject jsonObject = new JSONObject();

        jsonObject.put("code", "ORDERPAID");

        //将jsonObject转换为OrderPaymentVO对象
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        //将package属性赋值
        vo.setPackageStr(jsonObject.getString("package"));


        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改

        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付

        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单

        //发现没有将支付时间 check_out属性赋值，所以在这里更新

        LocalDateTime check_out_time = LocalDateTime.now();

        //第二种方法拿到用户的订单id
        //拿到当前用户的userid
//        Long userId1 = BaseContext.getCurrentId();
//        Orders orders = new Orders();
//        orders.setUserId(userId1);
        //查询当前用户的订单数据
//        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId1);
//        Long orderId = ordersDB.getId();

        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time,orderId);

//        根据订单Id查询订单信息
       Orders orders = orderMapper.getById(orderId);
//        构建下单成功的返回数据
        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content",  "订单号：" + orders.getNumber());
        //向商家发送订单信息 JSONObject.toJSONString(map)将map转换为json字符串
        //log.info("向商家发送订单信息：{}", JSON.toJSONString(map));
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return vo;

    }

    //支付成功，修改订单状态(未调用)
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    //分页查询历史订单
    //status两种情况待付款和已取消
    @Override
    public PageResult pageQueryOrders(int pageNum, int pageSize, Integer status) {

        PageHelper.startPage(pageNum, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());


        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        //查询订单明细，封装到OrderVO中
        List<OrderVO> orderVOList = new ArrayList<>();
        if(page!=null && !page.isEmpty()){
            for (Orders orders : page) {
                Long id = orders.getId();

                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);

                orderVO.setOrderDetailList(orderDetails);
                orderVOList.add(orderVO);

            }
        }

        return PageResult.builder()
                .total(page.getTotal())
                .records(orderVOList)
                .build();

    }

    //查询订单详情Detail

    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);

        //查询订单明细
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    //取消订单
    @Override
    public void userCancelById(Long id) {
        Orders order = orderMapper.getById(id);
        if(order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        //此时订单状态为1（用户下单成功等待商家接单的界面）
        if (order.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setPayStatus(Orders.REFUND);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    //再来一单
    @Override
    public void repetition(Long id){

        Long userId = BaseContext.getCurrentId();

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
//        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
//            ShoppingCart shoppingCart = new ShoppingCart();
//
//            BeanUtils.copyProperties(x, shoppingCart);
//            shoppingCart.setUserId(userId);
//            shoppingCart.setCreateTime(LocalDateTime.now());
//
//            return shoppingCart;
//
//        }).collect(Collectors.toList());
        ArrayList<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCarts.add(shoppingCart);
        }
        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCarts);

    }

    //订单搜索(管理端)
    @Override
    public PageResult conditionsearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //查询订单数据
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        //查询订单明细，封装到OrderVO中
        List<OrderVO> orderVOList = new ArrayList<>();
        if(page!=null && !page.isEmpty()){
            for (Orders orders : page) {

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishes(orders);

                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);

            }
        }

        return PageResult.builder()
                .total(page.getTotal())
                .records(orderVOList)
                .build();

    }

    private String getOrderDishes(Orders orders) {

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        List<String> orderDishesList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishesList);//这里是将orderDishesList中的元素用""拼接在一起
    }

    //各个状态的订单数量统计(待接单 2 待配送 3 派送中 4)
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.countByStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setConfirmed(orderMapper.countByStatus( Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    //接单商家接单其实就是将订单的状态修改为“已接单”
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

//- 商家拒单其实就是将订单状态修改为“已取消”
//- 只有订单处于“待接单”状态时可以执行拒单操作
//- 商家拒单时需要指定拒单原因
//- 商家拒单时，如果用户已经完成了支付，需要为用户退款
    //商家拒单
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        //只要拒单就是退款
        orders1.setPayStatus(Orders.REFUND);
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders1.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders1);
    }

//- 取消订单其实就是将订单状态修改为“已取消”
//- 商家取消订单时需要指定取消原因
//- 商家取消订单时，如果用户已经完成了支付，需要为用户退款
    //商家取消订单
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        orders.setId(orders.getId());
        //只要取消就是退款
        orders.setPayStatus(Orders.REFUND);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    //派送订单- 派送订单其实就是将订单状态修改为“派送中”
    //- 只有状态为“待派送”的订单可以执行派送订单操作

    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);
        //订单状态 1待付款 2待接单 3已接单“待派送” 4派送中 5已完成 6已取消
        if (orders == null || !orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        orders1.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders1);
    }

    //完成订单 - 完成订单其实就是将订单状态修改为“已完成”
    //- 只有状态为“派送中”的订单可以执行订单完成操作
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);
        //订单状态 1待付款 2待接单 3已接单 4派送中“已完成” 5已完成 6已取消
        if (orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        orders1.setStatus(Orders.COMPLETED);
        orderMapper.update(orders1);
    }

    //催单
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //构建催单消息
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        //向商家发送催单信息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    //检查客户的收货地址是否超出配送范围
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 1000000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

}
